package com.design.graduation.asdemo.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.design.graduation.asdemo.dao.migration.Migration;
import com.design.graduation.asdemo.dao.migration.V1Migration;

import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;



/**
 * Created by liyugang on 11/26/15.
 */
public class HSFOpenHelper extends DaoMaster.OpenHelper {

    private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<Integer,
            Migration>();

    static {
        ALL_MIGRATIONS.put(0, new V1Migration());
//        ALL_MIGRATIONS.put(1, new V2Migration());

    }

    public HSFOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        executeMigrations(db, ALL_MIGRATIONS.keySet());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        com.orhanobut.logger.Logger.d("Upgrading database from version " + oldVersion + " to " + newVersion);
        SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
        executeMigrations(db, migrations.keySet());
    }

    private void executeMigrations(final SQLiteDatabase paramSQLiteDatabase, final Set<Integer>
            migrationVersions) {
        for (final Integer version : migrationVersions) {

            ALL_MIGRATIONS.get(version).migrate(paramSQLiteDatabase);
        }
    }
}
